import * as path from 'path';  // node内置模块。
import * as vscode from 'vscode';

// 树节点
class EntryItem extends vscode.TreeItem {
    constructor(label: string) {
        super(label);
        this.label = label;
        this.iconPath = path.join(__dirname, '../resources/icon.png');
    }
}

//正在热映
export class SidebarHot implements vscode.TreeDataProvider<EntryItem>
{
    onDidChangeTreeData?: vscode.Event<void | EntryItem | null | undefined> | undefined;
    getTreeItem(element: EntryItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: EntryItem): vscode.ProviderResult<EntryItem[]> {
        if (!element) {
            return getMovieList(true);
        }
    }
}
//即将上映
export class SidebarSoon implements vscode.TreeDataProvider<EntryItem>
{
    onDidChangeTreeData?: vscode.Event<void | EntryItem | null | undefined> | undefined;
    getTreeItem(element: EntryItem): vscode.TreeItem | Thenable<vscode.TreeItem> {
        return element;
    }
    getChildren(element?: EntryItem): vscode.ProviderResult<EntryItem[]> {
        if (!element) {
            return getMovieList(false);
        }
    }
}
//返回电影列表
function getMovieList(this: any, flag: boolean) {
    let json = getMovieData() + "";   //buffer转字符串
    let obj = JSON.parse(json);  //解析json 
    let movies: any[] = [];
    for (let item of obj) {
        if (item["bool_showed"] === flag) {  //正在热映
            let movieName = new EntryItem(item["movie_name"]);
            movieName.command = {
                command: "sidebar_item.openWebview", //命令id
                title: "标题",
                arguments: [item] //命令接收的参数
            };
            movies.push(movieName);
        }
    };
    return movies;
}
//执行py文件，获取正在热映和即将上映电影列表 
function getMovieData() {
    let json = {};
    const { spawnSync } = require('child_process');  //同步
    let pyPath = path.join(__dirname, '../api/api.py');
    const ls = spawnSync('python', [pyPath]);
    json = ls.stdout;
    console.log(ls.stderr + ''); //输出错误信息
    return json;
}